package com.micro.ai.template.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.micro.ai.template.entity.AgentMetric;
import com.micro.ai.template.mapper.AgentMetricMapper;
import com.micro.ai.template.service.AgentMetricService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Agent指标Service实现
 *
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AgentMetricServiceImpl extends ServiceImpl<AgentMetricMapper, AgentMetric>
        implements AgentMetricService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void recordMetric(AgentMetric agentMetric) {
        if (agentMetric.getMetricDate() == null) {
            agentMetric.setMetricDate(LocalDate.now());
        }
        agentMetric.setCreatedAt(LocalDateTime.now());
        this.save(agentMetric);
    }

    @Override
    public List<AgentMetric> getMetrics(String agentId, LocalDateTime startTime, LocalDateTime endTime) {
        LambdaQueryWrapper<AgentMetric> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AgentMetric::getAgentId, agentId)
                .ge(AgentMetric::getMetricDate, startTime.toLocalDate())
                .le(AgentMetric::getMetricDate, endTime.toLocalDate())
                .orderByAsc(AgentMetric::getMetricDate);
        
        return this.list(wrapper);
    }

    @Override
    public Map<String, Object> getAggregatedMetrics(String agentId, String metricType,
                                                    LocalDateTime startTime, LocalDateTime endTime) {
        List<AgentMetric> metrics = getMetrics(agentId, startTime, endTime);
        
        Map<String, Object> result = new HashMap<>();
        if (!metrics.isEmpty()) {
            // 计算总请求数、成功数、失败数等
            int totalRequests = metrics.stream()
                    .mapToInt(m -> m.getTotalRequests() != null ? m.getTotalRequests() : 0)
                    .sum();
            int successfulRequests = metrics.stream()
                    .mapToInt(m -> m.getSuccessfulRequests() != null ? m.getSuccessfulRequests() : 0)
                    .sum();
            int failedRequests = metrics.stream()
                    .mapToInt(m -> m.getFailedRequests() != null ? m.getFailedRequests() : 0)
                    .sum();
            
            result.put("totalRequests", totalRequests);
            result.put("successfulRequests", successfulRequests);
            result.put("failedRequests", failedRequests);
            result.put("count", metrics.size());
            
            if (totalRequests > 0) {
                double successRate = (double) successfulRequests / totalRequests * 100;
                result.put("successRate", Math.round(successRate * 10.0) / 10.0);
            }
        }
        
        return result;
    }
}
